package com.flyduck.utils;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * <p>
 * JwtUtils
 * </p>
 *
 * @author flyduck
 * @since 2024-05-28
 */
@Data
@Component
@ConfigurationProperties(prefix = "jwt")
public class JwtUtils {

    //秒
    private long expire;
    private String secret;
    private String header;

    //生成jwt
    public String generateToken(String username){

        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);

        return Jwts.builder()
            .setHeaderParam("typ", "JWT")
            .setSubject(username)
            .setIssuedAt(nowDate)
            .setExpiration(expireDate) //设置7天过期
            .signWith(SignatureAlgorithm.HS512,secret)
            .compact();
    }


    //解析jwt
    public Claims getClaimsByToken(String token){
        try {
            return Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    //判断jwt是否过期
    public boolean isTokenExpired(Claims claims){
        //过期时间在今天之前就过期了
        return claims.getExpiration().before(new Date());
    }
}
